<?php namespace App\Api\Http\ApiControllers;

use App\Application\UserService;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    protected $user_service;

    public function __construct(UserService $user_service)
    {
        $this->user_service = $user_service;
    }

    /**
     * 通过code来获取登陆token
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $code = $request->get('code');
        $user_id = $request->get('user_id');
        $user_token = $this->user_service->getUserInfoByLoginCode($code, app('client')->ip, $user_id);

        if ($user_token) {
            return response()->json(array_only($user_token, 'token'));
        }

        return response()->json([], 400);
    }

    /**
     * 获取用户信息
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo()
    {
        $user = access()->user();
        $info = array_only($user->toArray(), ['id', 'uid', 'name', 'avatar']);
        $info['is_publisher'] = $user->isPublisher();

        return response()->json($info);
    }

    /**
     * 检查登录token是否有效
     *
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function checkToken()
    {
        if (access()->check()) {
            return response('', 204);
        }

        return response()->json(['error' => 'Unauthenticated.'], 401);
    }
}
